<?php
if( !defined('IN_INDEX') )
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}
date_default_timezone_set('Europe/Oslo');

	include('inc/config.php');
	include('inc/class_sql.php');
	include('inc/class_user.php');
	include('inc/functions.php');
	include 'inc/functions_like.php';
	
/*******************************************************************
**	SQL CONNECTION
** Connects to the MySql database
*******************************************************************/

$db = new sql_db($dbhost, $dbuser, $dbpasswd, $dbname);
if(!$db->db_connect_id)
{
	printError("DB CONNECT", "Could not connect to the DB, the DB is offline.
	<br />". mysql_error() ."<br />" . mysql_errno());
	// postErrorReport();
	exit;
}
unset($dbpasswd);
/**	SQL CONNECTION END **/

session_start();
session_name($SESSION_NAME);
$USER_IP=getVisitorIp();
$VISITOR_COUNTRY = getVisitorCountry($USER_IP);	// Checks which country the user visit from based on ip-address. Stored for later use
$LANG_LIST = getLangList('');
/*******************************************************************
**	LOGIN/LOGOUT
** Checks if the user is logging in our out and handles the request
*******************************************************************/
if(isset($_GET['logout']))
{
	$sql = "DELETE FROM sessions WHERE session_id='" . session_id() . "'";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	unset($_SESSION['user_id']);
}

if(isset($_SESSION['user_id']) && is_user_online($_SESSION['user_id']) == 0)
{
	unset($_SESSION['user_id']);
}

$MESSAGE['login_status'] = "";
if(isset($_POST['login_submit']) && !checkSession())
{
	if(isset($_POST['login_email']) && ($_POST['login_email'] != "")
		&& isset($_POST['login_password']) && ($_POST['login_password'] != ""))
	{
		$login_status = user_checkLogin($_POST['login_email'], $_POST['login_password']);
		switch($login_status)
		{
			case 1:	// Account disabled
				$MESSAGE['login_status'] = 'userisnotactive';
				header('Location: index.php?action=login&error=1');
				break;
				
			case 2:	// Success
				$MESSAGE['login_status'] = 'login_success';
				$USER = new User('email', $_POST['login_email']);
				$USER->setLastlogin(time());
				$USER->update();
				$_SESSION['user_id'] = $USER->getId(); // user_id
				header('Location: index.php?action=home');
				break;
				
			default: // Missmatch email/password
				$MESSAGE['login_status'] = 'invalidlogin';
				header('Location: index.php?action=login&error=0');
				break;
		}
	}
}
else if(checkSession())
{
	$USER = new user('id', $_SESSION['user_id']);
	$CONFIG['date_format'] = $USER->getDateFormat();
	$CONFIG['date_format_long'] = $USER->getDateFormatLong();
	
	// Set sessions
	$_SESSION['name'] = $SESSION_NAME; // ThePowerlifters
	$_SESSION['user_email'] = $USER->getEmail(); // User Email
	$_SESSION['firstname'] = $USER->getFirstname(); // User firstname
	$_SESSION['lastname'] = $USER->getLastname(); // User firstname
	
	// Imagemanager
	$_SESSION['isLoggedIn'] = true;
	$_SESSION['imagemanager.filesystem.path'] = './../../../../user_data/';
    $_SESSION['imagemanager.filesystem.rootpath'] = './../../../../user_data/'. $USER->getId() .'/';
	
	// Create user folder if not exists
	$directory = "user_data/".$USER->getId()."";
	if (!file_exists ( $directory )) {
	mkdir($directory);
	}
	
/**
*	Code to check session status. (active/inactive)
**/
	
	$time_org = date("H:i:s");
	$tz = $USER->getTimezone();
	$tzid = 0;
	if($tz != "")
	{
		foreach($TIME_ZONES as $k => $v)
		{
			if($tz == $v['gmt'])
			{
				$timezone = $v['timezone'];
				$tzid = $k;
			}
		}
		//$timezone = $TIME_ZONES[$tz];
	}
	date_default_timezone_set($timezone);
	$time_new = date("H:i:s");

	
	//	LANG SELECT(USER)
	// Selects the language file based on user settings
	$user_lang = $USER->getLang();
	switch(strtoupper($user_lang))
	{
		case 'US':
		case 'UK':
		case 'GB':
			$langfile ='lang_en'; break;
		case 'NO':
			$langfile = 'lang_no'; break;
		default:
			$langfile = 'lang_' . $USER->getLang(); break;
	}
	$langfile = strtolower($langfile);

	if(!file_exists('lang/' . $langfile . '.php'))
	{
		 $langfile = $CONFIG['default_lang'];
	}
	// LANG SELECT(USER) END
	}
	else
	{
	//	LANG SELECT
	// Selects the language file based on visitor country
	$default_lang = strtolower(getLangByCountry($VISITOR_COUNTRY));
	if(file_exists('lang/lang_' . $default_lang . '.php'))
	{
		$langfile = 'lang_' . $default_lang;
	}
	else
	{
		$langfile = $CONFIG['default_lang'];
	}
	// LANG SELECT END
}
/**	LOGIN/LOGOUT END **/

// LANG INCLUDE
include('lang/' . $CONFIG['default_lang'] . '.php');	// Includes all default values before including the current lang file
	if($langfile != $CONFIG['default_lang'])
	{
		include('lang/' . $langfile . '.php');	// Includes new lang file to replace default values to new language
	}

// LANG INCLUDE END

/*******************************************************************
**	SET INCLUDE PAGE
** Checks what content page to include based on $_REQUEST['action']
** or $_REQUEST['sub']. This also includes wether to show the 
** submenu and what to display there.
*******************************************************************/
if(isset($_REQUEST['action']) && $_REQUEST['action'] != "")
{
	$ACTION = $_REQUEST['action'];
}
else
{
	$ACTION = "login";
}

$SUBMENU_LIST = fetch_submenu($ACTION);
if(isset($_REQUEST['sub']) && $_REQUEST['sub'] != "")
{
	$SUB_ACTION = $_REQUEST['sub'];
}
else
{
	$SUB_ACTION = "";
}
$include_sidebar = activate_sidebar($ACTION);

if(isset($SUB_ACTION) && ($SUB_ACTION != ""))
{

	$INCLUDE_PAGE = "page/" . $ACTION . "_" . $SUB_ACTION . ".php";
	if(!file_exists($INCLUDE_PAGE))
	{
		$INCLUDE_PAGE = "page/" . $ACTION . ".php";
	}
}
else
{
	$INCLUDE_PAGE = "page/" . $ACTION . ".php";
}
if(!file_exists($INCLUDE_PAGE))
{
	$INCLUDE_PAGE = "page/login.php";
}
/**	SET INCLUDE PAGE END **/
?>